package com.itc.bpm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itc.bpm.bean.BpmFormDesign;
import com.itc.bpm.bean.BpmModel;
import com.itc.bpm.bean.BpmProcessCategory;
import com.itc.bpm.bean.BpmProcessInstanceExt;
import com.itc.bpm.service.BpmFormDesignService;
import com.itc.bpm.service.BpmModelService;
import com.itc.bpm.service.BpmProcessCategoryService;
import com.itc.bpm.service.BpmProcessInstanceExtService;
import com.itc.bpm.vo.BpmConditionVo;
import com.itc.common.core.domain.R;
import com.itc.common.core.utils.StringUtils;
import com.itc.common.core.validate.Add;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "流程模型管理接口")
@RestController
@Api(tags = "流程模型管理接口")
@RequestMapping("/bpm/model")
public class BpmModelController {

    @Autowired
    BpmModelService bpmModelService;

    @Autowired
    BpmFormDesignService bpmFormDesignService;

    @Autowired
    @Lazy
    BpmProcessInstanceExtService bpmProcessInstanceExtService;

    @ApiOperation(value = "获取模型xml")
    @GetMapping("/getXml/{id}")
    public R getModel(@PathVariable("id") Long id){
        BpmModel bpmModel = bpmModelService.getById(id);
        return R.ok(bpmModel.getBpmnXml());
    }

    @ApiOperation(value = "获取模型")
    @GetMapping("/getModelById/{id}")
    public R getModelById(@PathVariable("id") Long id){
        BpmModel bpmModel = bpmModelService.getById(id);
        return R.ok(bpmModel);
    }

    @ApiOperation(value = "根据流程key 获取流程模型list")
    @GetMapping("/getModelByCategory/{code}/{serviceId}")
    public R getModelByCategory(@PathVariable("code") String code,@PathVariable("serviceId") String serviceId){
        BpmModel bpmFormDesign = new BpmModel();
        bpmFormDesign.setDelFlag(0);
        bpmFormDesign.setStatus(0);
        bpmFormDesign.setIsDeploy(1);
        LambdaQueryWrapper<BpmModel> queryWrapper = new LambdaQueryWrapper<>(bpmFormDesign);
        String[] arr = code.split(",");
        queryWrapper.in(BpmModel::getBpmKey,arr);
        queryWrapper.orderByDesc(BpmModel::getCreateTime);
        List<BpmModel> resultPage = bpmModelService.list(queryWrapper);
        if(resultPage!=null && resultPage.size()>0){
            for(BpmModel item:resultPage){
                BpmProcessInstanceExt ext = bpmProcessInstanceExtService.findModelByModelKey(item.getBpmKey(),serviceId);
                if(ext!=null){
                    item.setIsStartStatus(ext.getStatus());
                }else{
                    item.setIsStartStatus(-1);
                }
            }
        }
        return R.ok(resultPage);
    }

    @PostMapping("/page")
    @ApiOperation(value = "流程模型分页")
    public R<Page<BpmModel>> getPage(@RequestBody BpmModel bpmFormDesign)
    {
        Page<BpmModel> page = new Page<>();
        page.setOptimizeCountSql(true);
        page.setSize(bpmFormDesign.getSize());
        page.setCurrent(bpmFormDesign.getCurrent());
        bpmFormDesign.setDelFlag(0);
        bpmFormDesign.setStatus(0);
        LambdaQueryWrapper<BpmModel> queryWrapper = new LambdaQueryWrapper<>(bpmFormDesign).orderByDesc(BpmModel::getCreateTime);
        Page<BpmModel> resultPage = bpmModelService.page(page,queryWrapper);
        return R.ok(resultPage);
    }

    @Autowired
    BpmProcessCategoryService bpmProcessCategoryService;
    @PostMapping("/list")
    @ApiOperation(value = "流程模型list")
    public R<List<BpmModel>> getList(@RequestBody BpmModel bpmFormDesign)
    {
        bpmFormDesign.setDelFlag(0);
        bpmFormDesign.setStatus(0);
        bpmFormDesign.setUseStatus(0);
        LambdaQueryWrapper<BpmModel> queryWrapper = new LambdaQueryWrapper<>(bpmFormDesign);
        if(bpmFormDesign.getType()!=null){
            List<String> categorys = null;
            List<BpmProcessCategory> list = bpmProcessCategoryService.list(new LambdaQueryWrapper<BpmProcessCategory>().eq(BpmProcessCategory::getType,bpmFormDesign.getType()));
            if(list!=null && list.size()>0){
                categorys = list.stream().map(BpmProcessCategory::getCode).collect(Collectors.toList());
                queryWrapper.in(BpmModel::getCategory,categorys);
            }
       }
       List<BpmModel> resultPage = bpmModelService.list(queryWrapper);
        return R.ok(resultPage);
    }


    @ApiOperation(value = "新增/修改 模型")
    @PostMapping(value = "/add",consumes = "application/json")
    public R addModel(@RequestBody BpmModel bpmModel){
        return bpmModelService.addModel(bpmModel);
    }

    @ApiOperation(value = "模型 部署")
    @GetMapping("/deploy/{id}")
    public R deployModel(@PathVariable("id") Long id){
        return bpmModelService.deployModel(id);
    }


    @ApiOperation(value = "删除 模型")
    @DeleteMapping("/delete/{id}")
    public R deleteModel(@PathVariable("id") Long id){
        BpmModel bpmModel = bpmModelService.getById(id);
        if(bpmModel==null){
            return R.fail("流程模型不存在");
        }
        if(bpmModel.getUseStatus()==null && bpmModel.getUseStatus()!=1){
            return R.fail("流程模型先停用后才能进行删除操作");
        }
        bpmModel.setDelFlag(1);
        bpmModelService.updateById(bpmModel);
        return R.ok();
    }

    @ApiOperation(value = "启用停用流程")
    @GetMapping("/startModel/{id}")
    public R startModel(@PathVariable("id") Long id){
        BpmModel bpmModel = bpmModelService.getById(id);
        if(bpmModel==null){
            return R.fail("流程模型不存在");
        }
        if(bpmModel.getUseStatus()==null || bpmModel.getStatus()==0){
            bpmModel.setUseStatus(1);
        }else{
            bpmModel.setUseStatus(0);
        }
        bpmModelService.updateById(bpmModel);
        return R.ok();
    }

    @ApiOperation(value = "根据模型bpmKey获取模型历史版本")
    @GetMapping("/history/model/{bpmKey}")
    public R<List<BpmModel>> getModel(@PathVariable("bpmKey") String bpmKey){
        List<BpmModel> list = bpmModelService.list(new LambdaQueryWrapper<BpmModel>().eq(BpmModel::getBpmKey,bpmKey).orderByDesc(BpmModel::getCreateTime));
        return R.ok(list);
    }
    @ApiOperation(value = "根据条件查询表单信息及字段信息")
    @PostMapping(value = "/getConditiobField",consumes = "application/json")
    public R<List<BpmFormDesign>> getConditiobField(@RequestBody BpmConditionVo conditionVo){
        String[] formCode =null;
        if(StringUtils.isNotEmpty(conditionVo.getFormCode())){
            formCode = conditionVo.getFormCode().split(",");
        }else if(conditionVo.getModelId()!=null){
           BpmModel bpmModel = bpmModelService.getById(conditionVo.getModelId());
           if(StringUtils.isNotEmpty(bpmModel.getFormCode())){
               formCode = bpmModel.getFormCode().split(",");
           }
        }
        if(formCode!=null){
            List<BpmFormDesign> list = bpmFormDesignService.list(new LambdaQueryWrapper<BpmFormDesign>().eq(BpmFormDesign::getDelFlag,0).eq(BpmFormDesign::getStatus,0).in(BpmFormDesign::getCode,formCode));
            return R.ok(list);
        }
       return R.ok(new ArrayList<>());
    }




}
